import React, {Component} from 'react';
import {
	AppRegistry,
	StyleSheet,
	Image,
	Text,
	Alert,
    ListView,
    TouchableOpacity,
    TouchableHighlight,
    DeviceEventEmitter,
	View
} from 'react-native';
import Style from './Style.js';
import SQLite from './SQLite.js';
var sqLite = new SQLite();
var db;
export default class Detail extends Component {
    constructor(props) {
		super(props);
        this.state = {
			data: null,
            dataSource:new ListView.DataSource({
                rowHasChanged:(row1,row2)=> row1 !== row2,
            }),
            balances: 0,
            expense:0,
            income:0,
            refresh: false,
		};
        this.lock = false;
	}

    componentWillUnmount(){
        this.refreshs.remove();    
        this.lock = true;         
		// sqLite.close();
	}

	componentWillMount(){
		if(!db){
			db=sqLite.open();
		}
		sqLite.createTable();
	}

    componentDidMount(){
        this.refreshs = DeviceEventEmitter.addListener('moduleChange',(moduleName) => {
            if (!this.lock) {
                this.setState({
                    refresh: !this.state.refresh,
                });
            }
        })
    }

    render(){
        var firstDate = new Date();  
        firstDate.setDate(1); //第一天  
        firstDate.setHours(0);
        var endDate = new Date(firstDate);  
        endDate.setMonth(firstDate.getMonth()+1);  
        endDate.setDate(0); 
        endDate.setHours(23);
        sqLite.listPaymentsByTime(firstDate.valueOf(),endDate.valueOf()).then(
            (datas) => {
                if (!this.lock) {
                    let payments = 0;
                    let incomes = 0;
                    for(let i=0; i<datas.length; i++){
                        if (datas[i].money < 0){
                            payments = payments - datas[i].money;
                        } else {
                            incomes = incomes + datas[i].money;
                        }
                    }
                    this.setState({
                        dataSource: this.state.dataSource.cloneWithRows(datas),
                        balances: incomes - payments,
                        expense: payments,
                        income: incomes,
                    });
                }
            },(error)=>{}
        ).catch(function(error){
                console.log("失败了",error);
                process.exit(1);
        });
        return(
            <View style={Style.detailContainer}>
                <View style={Style.detailDisplayContainer}>
                    {this._renderDisplayView()}
                </View>
                <View style={Style.detailOverViewContainer}>
                    {this._renderOverView()}
                </View>
                <View style={Style.detailListContainer}>
                    {this._renderListView()}
                </View>
                <TouchableOpacity onPress={this.addBtnPress.bind(this)} style={Style.detailAddBtnContainer} activeOpacity = {0.9}>
                            <Image style={Style.addIcon} source={require('./images/ic_new_main.png')}/>
                </TouchableOpacity>
            </View>
        );
    }

    addBtnPress(){
        this.props.goto.navigate('InputModule');
    }

    gotoChart(){
        this.props.goto.navigate('Chart');
    }

    _renderDisplayView(){
        return (
            <View style={Style.detailDisplay}>
                <Text style={Style.detailTitle}>Cost Amount</Text>
                <Text style={Style.detailNumber}>{this.state.balances}</Text>
                <View style={Style.line}></View>
                <Text style={Style.detailBudget}>Month Income : {this.state.income}</Text>
            </View>
        );
    }

    _renderOverView(){
        return(
            <TouchableOpacity style={Style.overViewDisplay} activeOpacity={0.9} onPress={this.gotoChart.bind(this)}>
                <Text style={Style.overViewText1}>Overview</Text>
                <Text style={Style.overViewText2}>view all ></Text>
            </TouchableOpacity>
        );
    }

    _renderListView(){
            return(
                <ListView
                    dataSource={this.state.dataSource}
                    enableEmptySections={true}
                    renderRow={(rowData) => {
                        return this._renderPayment(rowData);
                    }}
                    contentContainerStyle={Style.list}
                    style={Style.listView}
                />
            );
    }

    _renderPayment(payment){
        let moneys = parseInt(payment.money);
        if (moneys > 0) {
            return (
                <View style={Style.item}>
                    <Image style={Style.itemIcon} source = {require('./images/income.png')}/>
                    <Text style={Style.itemType}>{payment.type}</Text>
                    <Text style={Style.itemText}>{"+"+payment.money}</Text>
                </View>
            );
        } else {
            return (
                <View style={Style.item}>
                    <Image style={Style.itemIcon} source = {require('./images/expense.png')}/>
                    <Text style={Style.itemType}>{payment.type}</Text>
                    <Text style={Style.itemTextPayment}>{payment.money}</Text>
                </View>
            );
        }
    }
}
